package com.wangfa.provider.controller;

import com.wangfa.entity.House;
import com.wangfa.entity.MyPage;
import com.wangfa.entity.Student;
import com.wangfa.provider.repository.HouseRepository;
import com.wangfa.provider.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.List;

@RestController
@RequestMapping("student")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private HouseRepository houseRepository;

    @RequestMapping("list")
    public MyPage<Student> list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "3") int pageSize){
        PageRequest of = PageRequest.of(pageNum-1, pageSize);//page对象
        Page<Student> all = studentRepository.findAll(of);
    for (int i=0;i<all.getContent().size();i++){
        List<House> houseList = all.getContent().get(i).getHouseList();
        for(int j=0;j<houseList.size();j++){
            String coursename = houseList.get(j).getCoursename();
            if(coursename.equals("语文")){
                all.getContent().get(i).setYuwen(houseList.get(j).getFraction());
            }
            if(coursename.equals("数学")){
                all.getContent().get(i).setShuxue(houseList.get(j).getFraction());
            }
            if(coursename.equals("英语")){
                all.getContent().get(i).setYingyu(houseList.get(j).getFraction());
            }
            if(coursename.equals("物理")){
                all.getContent().get(i).setWuli(houseList.get(j).getFraction());
            }
            if(coursename.equals("化学")){
                all.getContent().get(i).setHuaxue(houseList.get(j).getFraction());
            }
            if(coursename.equals("生物")){
                all.getContent().get(i).setShengwu(houseList.get(j).getFraction());
            }


        }
    }
        MyPage<Student> studentMyPage = new MyPage<>(all);
        return studentMyPage;
    }


    @RequestMapping("add")

    public boolean edit(@RequestBody Student student){
        try {
            studentRepository.save(student);
            List<House> shouse = student.getShouse();
            for(House h:shouse){
                h.setStuid(student.getId());
                houseRepository.save(h);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;

    }


    @RequestMapping("delete")
    public boolean delete(int id){

        try {
            studentRepository.deleteById(id);
            houseRepository.removeHouseByStuid(id);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }








}
